package cn.stard.pet.service.impl;

import cn.stard.basic.util.BaiduAuditUtils;
import cn.stard.basic.util.LoginContext;
import cn.stard.pet.domain.Pet;
import cn.stard.pet.domain.PetDetail;
import cn.stard.pet.domain.PetOnlineAuditLog;
import cn.stard.pet.mapper.PetDetailMapper;
import cn.stard.pet.mapper.PetMapper;
import cn.stard.pet.mapper.PetOnlineAuditLogMapper;
import cn.stard.pet.service.IPetService;
import cn.stard.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stard
 * @since 2022-07-16
 */
@Service
public class PetServiceImpl extends BaseServiceImpl<Pet> implements IPetService {
    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Autowired
    private PetOnlineAuditLogMapper petOnlineAuditLogMapper;

    @Override
    public void remove(Long id) {
        petMapper.remove(id);
        petDetailMapper.remove(id);
    }



    @Override
    public void save(Pet pet) {
        // 1.保存宠物
        petMapper.save(pet);
        // 2.设置宠物详情关联宠物
        // 获取到宠物简介的对象
        PetDetail detail = pet.getDetail();
        // 判断详情是否为空不为空保存
        if (detail!=null){
        // 因为他们两个的数值一样所以重新赋值
            detail.setPetId(pet.getId());

            // 3.重新保存宠物详情
            petDetailMapper.save(detail);
        }


    }

    @Override
    public void update(Pet pet) {
        // 把宠物进行修改
        petMapper.update(pet);
        // 通过包含的获取到宠物信息
        PetDetail detail = pet.getDetail();
        if (detail!=null){
        // 根据获取到id添加到里面
            detail.setPetId(pet.getId());
            // 修改的参数就是同步跟新的id
        petDetailMapper.update(detail);
        }
    }

    // 宠物批量上架
    @Override
    public void onsale(List<Long> ids) {
        // 遍历Ids
        for (Long id : ids) {
            // 1.得到每个宠物基本信息对象
            Pet pet = petMapper.loadById(id);
            StringBuffer sbf = new StringBuffer();
            // 2.调用百度AI进行文字，图片的审核
            if (!BaiduAuditUtils.TextCensor(pet.getName())){
                sbf.append("宠物名称不合法，宠物名称为：" + pet.getName());
            }
            /*if (!BaiduAuditUtils.ImgCensor("123.207.27.208" + pet.getResources().split(",")[0])){
                sbf.append("宠物图片不合法，宠物图片路径：" + pet.getResources().split(",")[0]);
            }*/
            if (sbf.length() > 0){
                // 2.1.如果违规，我们要保存审核失败日志
                PetOnlineAuditLog petOnlineAuditLog = new PetOnlineAuditLog();
                petOnlineAuditLog.setPetId(id);
                petOnlineAuditLog.setNote(sbf.toString());
                petOnlineAuditLogMapper.save(petOnlineAuditLog);
                continue;
            }
            petMapper.onsale(id);
        }

    }

    // 宠物批量下架
    @Override
    public void offsale(List<Long> ids) {
        petMapper.offsale(ids);
    }

}
